<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Http\Controllers;

use App\Enums\UploadEnum;
use App\Exceptions\ApiException;
use App\Services\ImageService;
use Illuminate\Http\Request;

class ImagesController extends Controller
{
    protected $imageService;

    public function __construct(ImageService $imageService)
    {
        $this->imageService = $imageService;
    }

    /**
     * 图片上传/批量上传：100k以下，需做名称重复校验，不可上传相同名称图片；.
     */
    public function upload(Request $request)
    {
        $file = $request->file('file');
        if (empty($file)) {
            throw new ApiException('缺少参数', 1);
        }
        if ($file->getSize() > UploadEnum::UPLOAD_BACKGROUND_SIZE) {
            throw new ApiException('文件体积过大, 应小于 100kb, 当前大小为 ' . ceil($file->getSize() / 1024) . 'kb', 1);
        }
        $path = $this->imageService->upload($file);
        return renderSuccessJson($path);
    }

    /**
     * 添加图片.
     */
    public function create(Request $request)
    {
        $url = $request->input('url');
        $title = $request->input('title') ?? '';
        $render_mode = $request->input('render_mode');

        if (empty($url) || empty($render_mode) || empty($title)) {
            throw new ApiException('缺少参数', 1);
        }

        $this->imageService->create($url, $title, $render_mode);

        return renderSuccessJson();
    }

    public function update(Request $request)
    {
        $id = $request->input('id');
        $render_mode = $request->input('render_mode');
        if (empty($id) || empty($render_mode)) {
            throw new ApiException('缺少参数', 1);
        }
        $this->imageService->update($id, $render_mode);
        return renderSuccessJson();
    }

    public function delete(Request $request)
    {
        $id = $request->input('id');

        if (empty($id)) {
            return renderErrorJson('1', '缺少参数');
        }

        $this->imageService->delete($id);

        return renderSuccessJson();
    }

    public function list(Request $request)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 10);
        $search = [];
        if ($request->input('title')) {
            $search['title'] = $request->input('title');
        }
        $res = $this->imageService->getList($page, $pageSize, $search);
        return renderSuccessJson($res);
    }
}
